const execSync = require('child_process').execSync;

class WebpackModuleConfig {
  constructor(options) {
    this.options = options;
  }

  apply(compiler) {
    let entryFiles = [];
    compiler.hooks.emit.tapAsync('WebpackModuleConfig', (complication, callback) => {
      const mainComplication = complication;
      const group = mainComplication.chunks.filter(chunk => chunk.entryModule).reduce((acc, chunk) => {
        const { name, files } = chunk;
        acc[name] = {
          entry: files,
          hash: mainComplication.hash,
          date: new Date().toUTCString()
        };
        entryFiles = entryFiles.concat(files);
        return acc;
      }, {});

      const gitInfo = {
        commit: execSync('git log -1 --pretty=format:%h').toString(),
        'commit-date': execSync('git log -1 --pretty=format:%ci').toString()
      };
      const manifest = {
        name: this.options.name,
        version: this.options.version,
        ...gitInfo,
        ...group
      };

      const configManifest = JSON.stringify(manifest);
      mainComplication.assets['manifest.json'] = {
        source: () => configManifest,
        size: () => configManifest.length
      };

      callback();
    });
  }
}

module.exports = WebpackModuleConfig;
